﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Mindfor.Web.Data;
using Mindfor.Web.Routing;

namespace Mindfor.Web.Modules.System.Controllers
{
	/// <summary>
	/// Provides manipulation with modules.
	/// </summary>
	[CmsAuthorize(CmsRoles.Administrator)]
	public class ModulesController : CmsController
	{
		/// <summary>
		/// Returns view result with modules.
		/// </summary>
		[UrlRoute(Path="Admin/Modules")]
		[AdminLink("Модули", "Системные")]
		public ActionResult Index()
		{
			ViewData.Model = ModuleFactory.Default.Modules;
			return View();
		}

		/// <summary>
		/// Applies modules enable changes.
		/// </summary>
		[HttpPost]
		[UrlSubAction("Index")]
		[UrlRoute(Path="Admin/Modules", SubPath="Apply")]
		public ActionResult Apply(FormCollection form)
		{
			foreach (ModuleBase m in ModuleFactory.Default.Modules)
			{
				string key = m.Name + ".IsEnabled";
				bool? isEnabled = form.EvalBool(key);
				if (isEnabled.HasValue)
					m.IsEnabled = isEnabled.Value;
			}

			ModuleFactory.Default.SaveIsEnabled(Data);
			CmsApplication.Restart();
			return RedirectToAction("Index");
		}

		/// <summary>
		/// Returns view result with one module.
		/// </summary>
		[UrlSubAction("Index")]
		[UrlRoute("{name}", Path="Admin/Modules")]
		public ActionResult Item(string name)
		{
			ModuleBase m = ModuleFactory.Default.Modules[name];
			if (m == null)
				return HttpNotFound();
			return View(m);
		}
	}
}
